package com.alibaba.citrus.cr.common.util;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.result.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;

@Component
public class EpochRESTClient {
    private static final Log log = Log.getLogger(EpochRESTClient.class);

    @Value("${epoch.rest.domain}")
    private String domain;

    @Value("${epoch.rest.ak}")
    private String ak;
    @Value("${epoch.rest.sk}")
    private String sk;
    @Resource
    private RestTemplate restTemplate;

    public Result request(String path,Object request){

        Date date = new Date();
        String timestamp = String.valueOf(date.getTime());
        log.info("timestamp："+timestamp);

//        String sk = "5q6sJqAtBY7g29oISb56Cwb9WWfrBa";
        String src =  timestamp+ak+sk;
        log.info("ak："+ak);
        log.info("sk："+sk);
        String token = getMD5(src);
        log.info("token："+ token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("timestamp",timestamp);
        httpHeaders.set("ak",ak);
        httpHeaders.set("token", token);

        // 封装参数和头信息
        HttpEntity<Object> httpEntity = new HttpEntity(request,httpHeaders);
        String actualDomain = domain;
        Result result = restTemplate.postForObject(actualDomain+path, httpEntity, Result.class);
        log.info("epoch rest request,url={},req={},res={}",domain+path, JSON.toJSONString(request), JSON.toJSONString(result));
        return result;
    }

    public Object request(String path,Object request, Class clazz){

        Date date = new Date();
        String timestamp = String.valueOf(date.getTime());
        log.info("timestamp："+timestamp);

//        String sk = "5q6sJqAtBY7g29oISb56Cwb9WWfrBa";
        String src =  timestamp+ak+sk;
        log.info("ak："+ak);
        log.info("sk："+sk);
        String token = getMD5(src);
        log.info("token："+ token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("timestamp",timestamp);
        httpHeaders.set("ak",ak);
        httpHeaders.set("token", token);

        // 封装参数和头信息
        HttpEntity<Object> httpEntity = new HttpEntity(request,httpHeaders);
        String actualDomain = domain;
        log.info("epoch_rest_request,url={},req={}",domain+path, JSON.toJSONString(request));
        Object result = restTemplate.postForObject(actualDomain+path, httpEntity, clazz);
        log.info("epoch_rest_request,res={}",JSON.toJSONString(result));
        return result;
    }

    public <T> T requestResult(String path,Object request, Class<T> clazz){

        Date date = new Date();
        String timestamp = String.valueOf(date.getTime());
        log.info("timestamp："+timestamp);

//        String sk = "5q6sJqAtBY7g29oISb56Cwb9WWfrBa";
        String src =  timestamp+ak+sk;
        log.info("ak："+ak);
        String token = getMD5(src);
        log.info("token："+ token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("timestamp",timestamp);
        httpHeaders.set("ak",ak);
        httpHeaders.set("token", token);

        // 封装参数和头信息
        HttpEntity<Object> httpEntity = new HttpEntity(request,httpHeaders);
        String actualDomain = domain;
        return restTemplate.postForObject(actualDomain+path, httpEntity, clazz);
    }

    /**
     * rest请求（返回字符串）
     * @param path
     * @param request
     * @return
     */
    public String invoke(String path,Object request){

        Date date = new Date();
        String timestamp = String.valueOf(date.getTime());
        log.info("timestamp："+timestamp);

//        String sk = "5q6sJqAtBY7g29oISb56Cwb9WWfrBa";
        String src =  timestamp+ak+sk;
        log.info("ak："+ak);
        String token = getMD5(src);
        log.info("token："+ token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("timestamp",timestamp);
        httpHeaders.set("ak",ak);
        httpHeaders.set("token", token);

        // 封装参数和头信息
        HttpEntity<Object> httpEntity = new HttpEntity(request,httpHeaders);

        return restTemplate.postForObject(domain+path, httpEntity,String.class);
    }

    public static String getMD5(String src) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
       /* byte[] digest  = md5.digest(src.getBytes(StandardCharsets.UTF_8));
        return new BigInteger(1, digest).toString(16);*/

        md5.update(src.getBytes(StandardCharsets.UTF_8));
        byte[] digest = md5.digest();
        return DatatypeConverter.printHexBinary(digest).toLowerCase();
    }


}
